using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.AceEngineering.SPM.SPMDataLayer;
using Microsoft.ApplicationBlocks.Data;
using Microsoft.AceEngineering.SPM.SPMBusinessLayer;
using Microsoft.AceEngineering.SPM.SPMCustomDataEntity;

public partial class Admin_Workflow_Workflow : Page
{
    private int intMemLoaded;
    private string strUserID;
    private string dtCreatedDate = System.DateTime.Now.Date.ToShortDateString();
    private string strConn = ConfigurationManager.ConnectionStrings["SPMSQL"].ConnectionString.ToString();
    private System.IO.MemoryStream xmlStreamWF = new System.IO.MemoryStream();
    private System.IO.MemoryStream xmlStreamLC = new System.IO.MemoryStream();
    private System.IO.MemoryStream xmlStreamTS = new System.IO.MemoryStream();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
            ValidateUser();
        else
        {
            UserCDE userData = (UserCDE)Session["user"];
            if (userData.Time.AddMinutes(Int32.Parse(ConfigurationManager.AppSettings["AbsoluteExpiration"].ToString())) <= DateTime.Now)
                ValidateUser();
        }

        bool isAdmin = UsersBL.GetUserAdmin(Session["loginname"].ToString());
        if (!isAdmin)
            Response.Redirect("~/Home.aspx");

        strUserID = Session["loginname"].ToString();

        if (Page.IsPostBack == false)
        {
            BindWorkFlow();
            BindRepeater();
        }
    }

    private string GiveMeAlias(string domainAndAlias)
    {
        domainAndAlias = domainAndAlias.ToLower();
        char[] strSeperator = new char[] { '\\' };
        string[] aryAuthUser = new string[2];
        aryAuthUser = domainAndAlias.Split(strSeperator);
        return aryAuthUser[1];
    }

    private void ValidateUser()
    {
        string currAlias = GiveMeAlias(HttpContext.Current.User.Identity.Name);
        UserCDE user = UsersBL.ValidateUser(currAlias);
        if (user.Active)
        {
            Session["user"] = user;
            Session["loginname"] = user.UserAlias;
        }
        else
        {
            Response.Redirect(Request.ApplicationPath + "/Errors/NoAccess.htm");
        }
    }

    protected void BindWorkFlow()
    {
        DataTable dt = new DataTable();
        dt = dsLoadDataSet("SPM_spGetActiveWorkflow").Tables[0];
        if (dt.Rows.Count != 0)
        {
            txtWkfwID.Text = dt.Rows[0]["WorkflowID"].ToString();
            txtWkfwName.Text = dt.Rows[0]["WorkFlowName"].ToString();
            txtWorkFlowDesc.Text = dt.Rows[0]["Description"].ToString();
        }

    }
    protected void BindRepeater()
    {
        DataView dvLifeCycle = dsLoadDataSet("SPM_spGetLifeCycles").Tables[0].DefaultView;

        dvLifeCycle.RowFilter = "WorkFlowID='" + txtWkfwID.Text.ToUpper() + "'";
        dvLifeCycle.AddNew();

        rptLifeCycles.DataSource = dvLifeCycle;
        rptLifeCycles.DataBind();

        foreach (RepeaterItem riLifeCycle in rptLifeCycles.Items)
        {
            DataView dvTasks = dsLoadDataSet("SPM_spGetTasks").Tables[0].DefaultView;

            TextBox txtLifeCycleID = (TextBox)riLifeCycle.FindControl("txtLCID");
            dvTasks.RowFilter = "LifeCycleID='" + txtLifeCycleID.Text.ToUpper() + "'";
            dvTasks.AddNew();

            Repeater rptTasks = (Repeater)riLifeCycle.FindControl("rptTaskItems");
            rptTasks.DataSource = dvTasks;
            rptTasks.DataBind();
        }

    }
    protected DataSet dsLoadDataSet(string strStoredProc)
    {
        DataSet ds = new DataSet();

        if (intMemLoaded == 0)
        {
            // Create Instance of Connection and Command Object
            SqlConnection myConnection = new SqlConnection(strConn);

            myConnection.Open();
            SqlDataAdapter sda = new SqlDataAdapter(strStoredProc, myConnection);

            sda.Fill(ds);
            myConnection.Close();
        }
        else
        {
            if (strStoredProc == "SPM_spGetActiveWorkflow")
            {

                xmlStreamWF.Position = 0;
                System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(xmlStreamWF);
                ds.ReadXml(reader);
            }
            else if (strStoredProc == "SPM_spGetLifeCycles")
            {
                xmlStreamLC.Position = 0;
                System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(xmlStreamLC);
                ds.ReadXml(reader);
            }
            else
            {
                xmlStreamTS.Position = 0;
                System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(xmlStreamTS);
                ds.ReadXml(reader);
            }

        }

        return ds;
    }
    protected void WorkFlow_Save(object sender, EventArgs e)
    {
        Validate();
        if (!Page.IsValid)
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            // Loop through all validation controls to see which
            // generated the errors.
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");

        }
        else
        {

            #region Declaration of variables

            int i = 0;
            int cnt = 0;
            int intStatus = 1;

            #endregion

            #region Create WorkFlow datatable

            DataTable dtWorkFlow = new DataTable("Workflow");

            DataColumn[] colWorkflow = new DataColumn[6];
            colWorkflow[0] = new DataColumn("WorkFlowID", System.Type.GetType("System.String"));
            dtWorkFlow.Columns.Add(colWorkflow[0]);
            colWorkflow[1] = new DataColumn("WorkFlowName", System.Type.GetType("System.String"));
            dtWorkFlow.Columns.Add(colWorkflow[1]);
            colWorkflow[2] = new DataColumn("Description", System.Type.GetType("System.String"));
            dtWorkFlow.Columns.Add(colWorkflow[2]);
            colWorkflow[3] = new DataColumn("Status", System.Type.GetType("System.Int32"));
            dtWorkFlow.Columns.Add(colWorkflow[3]);
            colWorkflow[4] = new DataColumn("CreatedDate", System.Type.GetType("System.DateTime"));
            dtWorkFlow.Columns.Add(colWorkflow[4]);
            colWorkflow[5] = new DataColumn("CreatedBy", System.Type.GetType("System.String"));
            dtWorkFlow.Columns.Add(colWorkflow[5]);

            DataSet dsXML = new DataSet("SPMMasterWorkFlow");
            dsXML.Tables.Add(dtWorkFlow);
            #endregion

            #region Create Lifecycle datatable
            DataTable dtLifeCycles = new DataTable("LifeCycles");
            DataColumn[] colLifeCycle = new DataColumn[10];
            colLifeCycle[0] = new DataColumn("WorkFlowID", System.Type.GetType("System.String"));
            dtLifeCycles.Columns.Add(colLifeCycle[0]);
            colLifeCycle[1] = new DataColumn("LifeCycleID", System.Type.GetType("System.String"));
            dtLifeCycles.Columns.Add(colLifeCycle[1]);
            colLifeCycle[2] = new DataColumn("Active", System.Type.GetType("System.Int32"));
            dtLifeCycles.Columns.Add(colLifeCycle[2]);
            colLifeCycle[3] = new DataColumn("LifeCycleName", System.Type.GetType("System.String"));
            dtLifeCycles.Columns.Add(colLifeCycle[3]);
            colLifeCycle[4] = new DataColumn("Description", System.Type.GetType("System.String"));
            dtLifeCycles.Columns.Add(colLifeCycle[4]);
            colLifeCycle[5] = new DataColumn("CreatedDate", System.Type.GetType("System.DateTime"));
            dtLifeCycles.Columns.Add(colLifeCycle[5]);
            colLifeCycle[6] = new DataColumn("CreatedBy", System.Type.GetType("System.String"));
            dtLifeCycles.Columns.Add(colLifeCycle[6]);
            colLifeCycle[7] = new DataColumn("ModifiedBy", System.Type.GetType("System.String"));
            dtLifeCycles.Columns.Add(colLifeCycle[7]);
            colLifeCycle[8] = new DataColumn("ModifiedDate", System.Type.GetType("System.DateTime"));
            dtLifeCycles.Columns.Add(colLifeCycle[8]);
            colLifeCycle[9] = new DataColumn("Order", System.Type.GetType("System.Int32"));
            dtLifeCycles.Columns.Add(colLifeCycle[9]);

            DataSet dsXMLLC = new DataSet("SPMMasterLifeCycle");
            dsXMLLC.Tables.Add(dtLifeCycles);
            #endregion

            #region Create Tasks datatable
            DataTable dtTasks = new DataTable("Tasks");
            DataColumn[] colTasks = new DataColumn[7];
            colTasks[0] = new DataColumn("TaskID", System.Type.GetType("System.String"));
            dtTasks.Columns.Add(colTasks[0]);
            colTasks[1] = new DataColumn("LifeCycleID", System.Type.GetType("System.String"));
            dtTasks.Columns.Add(colTasks[1]);
            colTasks[2] = new DataColumn("TaskName", System.Type.GetType("System.String"));
            dtTasks.Columns.Add(colTasks[2]);
            colTasks[3] = new DataColumn("Description", System.Type.GetType("System.String"));
            dtTasks.Columns.Add(colTasks[3]);
            colTasks[4] = new DataColumn("CreatedDate", System.Type.GetType("System.DateTime"));
            dtTasks.Columns.Add(colTasks[4]);
            colTasks[5] = new DataColumn("CreatedBy", System.Type.GetType("System.String"));
            dtTasks.Columns.Add(colTasks[5]);
            colTasks[6] = new DataColumn("Active", System.Type.GetType("System.Int32"));
            dtTasks.Columns.Add(colTasks[6]);


            DataSet dsXMLTasks = new DataSet("SPMTasks");
            dsXMLTasks.Tables.Add(dtTasks);
            #endregion

            #region Fill Workflow datatable
            string strWFID = System.Guid.NewGuid().ToString().ToUpper();
            string strWFName = txtWkfwName.Text;
            string strWFDesc = txtWorkFlowDesc.Text;

            if (!string.IsNullOrEmpty(strWFName))
            {
                DataRow drWorkFlow = dtWorkFlow.NewRow();
                drWorkFlow["WorkFlowID"] = strWFID;
                drWorkFlow["WorkFlowName"] = strWFName;
                drWorkFlow["Description"] = strWFDesc;
                drWorkFlow["Status"] = intStatus;
                drWorkFlow["CreatedDate"] = dtCreatedDate;
                drWorkFlow["CreatedBy"] = strUserID;
                dtWorkFlow.Rows.Add(drWorkFlow);

            #endregion

                #region Fill Lifecycle datatable

                //Repeater rptLC = (Repeater)FindControl("rptLifeCycles");
                i = rptLifeCycles.Items.Count + 1;

                DataRow[] drLC = new DataRow[i];

                foreach (RepeaterItem riLC in rptLifeCycles.Items)
                {

                    string strLCID = System.Guid.NewGuid().ToString().ToUpper();
                    TextBox txtLCName = (TextBox)riLC.FindControl("txtLifeCycleName");
                    string strLCName = txtLCName.Text;

                    TextBox txtLCDesc = (TextBox)riLC.FindControl("txtLifecycleDesc");
                    string strLCDesc = txtLCDesc.Text;

                    if (!string.IsNullOrEmpty(strLCName))
                    {
                        drLC[cnt] = dtLifeCycles.NewRow();
                        drLC[cnt]["WorkFlowID"] = strWFID;
                        drLC[cnt]["LifeCycleID"] = strLCID;
                        drLC[cnt]["Active"] = intStatus;
                        drLC[cnt]["LifeCycleName"] = strLCName;
                        drLC[cnt]["Description"] = strLCDesc;
                        drLC[cnt]["CreatedDate"] = dtCreatedDate;
                        drLC[cnt]["CreatedBy"] = strUserID;
                        drLC[cnt]["ModifiedBy"] = strUserID;
                        drLC[cnt]["ModifiedDate"] = dtCreatedDate;
                        drLC[cnt]["Order"] = cnt + 1;
                        dtLifeCycles.Rows.Add(drLC[cnt]);
                    }
                    cnt = cnt + 1;


                #endregion

                    #region Fill Tasks datatable

                    Repeater rptTS = (Repeater)riLC.FindControl("rptTaskItems");
                    int t = 0;
                    t = rptTS.Items.Count + 1;
                    int cntTS = 0;

                    DataRow[] drTS = new DataRow[t];

                    foreach (RepeaterItem riTS in rptTS.Items)
                    {

                        string strTSID = System.Guid.NewGuid().ToString().ToUpper();

                        TextBox txtTaskName = (TextBox)riTS.FindControl("txtTSName");
                        string strTSName = txtTaskName.Text;

                        TextBox txtTaskDesc = (TextBox)riTS.FindControl("txtTSDesc");
                        string strTSDesc = txtTaskDesc.Text;

                        if (!string.IsNullOrEmpty(strTSName))
                        {
                            drTS[cntTS] = dtTasks.NewRow();
                            drTS[cntTS]["TaskID"] = strTSID;
                            drTS[cntTS]["LifeCycleID"] = strLCID;
                            drTS[cntTS]["Active"] = intStatus;
                            drTS[cntTS]["TaskName"] = strTSName;
                            drTS[cntTS]["Description"] = strTSDesc;
                            drTS[cntTS]["CreatedDate"] = dtCreatedDate;
                            drTS[cntTS]["CreatedBy"] = strUserID;
                            dtTasks.Rows.Add(drTS[cntTS]);
                        }
                        cntTS = cntTS + 1;
                    }
                }
            }
                    #endregion

            #region Write data to xml memory

            dsXML.WriteXml(xmlStreamWF, XmlWriteMode.IgnoreSchema);
            dsXMLLC.WriteXml(xmlStreamLC, XmlWriteMode.IgnoreSchema);
            dsXMLTasks.WriteXml(xmlStreamTS, XmlWriteMode.IgnoreSchema);
            intMemLoaded = 1;

            #endregion

            BindWorkFlow();
            BindRepeater();
        }
    }
    protected void WorkFlow_Submit(object sender, EventArgs e)
    {
        WorkFlow_Save(sender, e);
        SqlConnection scConn = new SqlConnection(strConn);
        scConn.Open();

        xmlStreamWF.Position = 0;
        xmlStreamLC.Position = 0;
        xmlStreamTS.Position = 0;

        StreamReader xmlWFStream = new StreamReader(xmlStreamWF);
        StreamReader xmlLCStream = new StreamReader(xmlStreamLC);
        StreamReader xmlTSStream = new StreamReader(xmlStreamTS);

        string strXMLWF = xmlWFStream.ReadToEnd().ToString();
        string strXMLLC = xmlLCStream.ReadToEnd().ToString();
        string strXMLTS = xmlTSStream.ReadToEnd().ToString();

        xmlWFStream.Dispose();
        xmlLCStream.Dispose();
        xmlTSStream.Dispose();

        strXMLWF = strXMLWF.Replace("T00:00:00-0[0-9]:00", "");
        strXMLLC = strXMLLC.Replace("T00:00:00-0[0-9]:00", "");
        strXMLTS = strXMLTS.Replace("T00:00:00-0[0-9]:00", "");

        try
        {
            SqlCommand scUpdate = new SqlCommand("SPM_spUploadWorkFlowLifeCycles", scConn);
            scUpdate.CommandType = CommandType.StoredProcedure;

            scUpdate.Parameters.Add("@XmlWFDocument", SqlDbType.Xml).Value = strXMLWF;
            scUpdate.Parameters.Add("@XmlLCDocument", SqlDbType.Xml).Value = strXMLLC;
            scUpdate.Parameters.Add("@XmlTSDocument", SqlDbType.Xml).Value = strXMLTS;

            scUpdate.ExecuteNonQuery();
            scUpdate.Dispose();
        }
        catch (Exception ex)
        {
            string strErrorType = ex.Message.ToString().Substring(0, 8);

            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
            if (!Request.IsLocal && strErrorType != "APMError")
            {
                Server.ClearError();
                Server.Transfer("~/Errors/GenericErrorPage.htm");
            }
        }
        finally
        {
            scConn.Close();
            Response.Redirect(Request.ApplicationPath + "/Home.aspx");
        }

    }
}
